package com.leadcloud.nim.main.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.leadcloud.nim.CommonCache;
import com.leadcloud.nim.NimApplication;
import com.leadcloud.nim.R;
import com.leadcloud.nim.config.preference.Preferences;
import com.leadcloud.nim.login.LoginActivity;
import com.leadcloud.nim.login.LogoutHelper;
import com.leadcloud.nim.main.fragment.HomeFragment;
import com.leadcloud.nim.session.SessionHelper;
import com.leadcloud.nim.team.TeamCreateHelper;
import com.netease.nim.uikit.api.model.main.LoginSyncDataStatusObserver;
import com.netease.nim.uikit.business.contact.selector.activity.ContactSelectActivity;
import com.netease.nim.uikit.common.MyConst;
import com.netease.nim.uikit.common.activity.UI;
import com.netease.nim.uikit.common.http.NimHttpClient;
import com.netease.nim.uikit.common.ui.dialog.DialogMaker;
import com.netease.nim.uikit.common.ui.popupmenu.NIMPopupMenu;
import com.netease.nim.uikit.common.ui.popupmenu.PopupMenuItem;
import com.netease.nim.uikit.common.util.log.LogUtil;
import com.netease.nim.uikit.common.util.sys.ScreenUtil;
import com.netease.nim.uikit.support.permission.MPermission;
import com.netease.nim.uikit.support.permission.annotation.OnMPermissionDenied;
import com.netease.nim.uikit.support.permission.annotation.OnMPermissionGranted;
import com.netease.nim.uikit.support.permission.annotation.OnMPermissionNeverAskAgain;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.NimIntent;
import com.netease.nimlib.sdk.Observer;
import com.netease.nimlib.sdk.auth.AuthService;
import com.netease.nimlib.sdk.msg.model.IMMessage;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 主界面
 */
public class MainActivity extends UI {

    private static final String EXTRA_APP_QUIT = "APP_QUIT";
    private static final int REQUEST_CODE_NORMAL = 1;
    private static final int REQUEST_CODE_ADVANCED = 2;
    private static final String TAG = MainActivity.class.getSimpleName();
    private static final int BASIC_PERMISSION_REQUEST_CODE = 100;

    private HomeFragment mainFragment;
    private NIMPopupMenu popupMenu;
    private PopupWindow popWindow;
    private TextView tv_main_title;

    public static void start(Context context) {
        start(context, null);
    }

    public static void start(Context context, Intent extras) {
        Intent intent = new Intent();
        intent.setClass(context, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        if (extras != null) {
            intent.putExtras(extras);
        }
        context.startActivity(intent);
    }

    // 注销
    public static void logout(Context context, boolean quit) {
        Intent extra = new Intent();
        extra.putExtra(EXTRA_APP_QUIT, quit);
        start(context, extra);
    }

    @Override
    public boolean isTransStatusBar() {
        return true;
    }

    @Override
    protected boolean displayHomeAsUpEnabled() {
        return false;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_tab);
        requestBasicPermission();

        onParseIntent();
        initView();

        // 等待同步数据完成
        boolean syncCompleted = LoginSyncDataStatusObserver.getInstance().observeSyncDataCompletedEvent(new Observer<Void>() {
            @Override
            public void onEvent(Void v) {
                DialogMaker.dismissProgressDialog();
            }
        });

        LogUtil.i(TAG, "sync completed = " + syncCompleted);
        if (!syncCompleted) {
            DialogMaker.showProgressDialog(MainActivity.this, getString(R.string.prepare_data)).setCanceledOnTouchOutside(false);
        }

        onInit();
    }

    private void initView() {
        findView(R.id.iv_logout).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showLogoutConfirmPop(view);
            }
        });
        tv_main_title = findView(R.id.tv_main_title);
        initPopupWindow();
    }

    public void setMainTitle(String title){
        tv_main_title.setText(title);
    }

    private void initPopupWindow() {
        if (popWindow == null) {
            //popWindow = new PopupWindow(rootView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
            ImageView rootView = new ImageView(this);
            rootView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (popWindow.isShowing()) {
                        popWindow.dismiss();
                    }
                    onLogout();
                }
            });
            rootView.setImageDrawable(getResources().getDrawable(R.mipmap.nav_btn_exit));
            popWindow = new PopupWindow(this);
            popWindow.setContentView(rootView);
            popWindow.setWidth(WindowManager.LayoutParams.WRAP_CONTENT);
            popWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
            popWindow.setTouchable(true);
            popWindow.setBackgroundDrawable(new BitmapDrawable());
        }
    }

    private void showLogoutConfirmPop(View v){
        if (popWindow.isShowing()) {
            popWindow.dismiss();
        } else {
            popWindow.setFocusable(true);

            popWindow.getContentView().measure(View.MeasureSpec.UNSPECIFIED,View.MeasureSpec.UNSPECIFIED);
            int i = popWindow.getContentView().getMeasuredWidth();

            popWindow.showAsDropDown(v, (int) (-i*0.68),-ScreenUtil.dip2px(6));
        }
    }

    /**
     * 基本权限管理
     */
    private final String[] BASIC_PERMISSIONS = new String[]{
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA,
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION
    };

    private void requestBasicPermission() {
        MPermission.printMPermissionResult(true, this, BASIC_PERMISSIONS);
        MPermission.with(MainActivity.this)
                .setRequestCode(BASIC_PERMISSION_REQUEST_CODE)
                .permissions(BASIC_PERMISSIONS)
                .request();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        MPermission.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    @OnMPermissionGranted(BASIC_PERMISSION_REQUEST_CODE)
    public void onBasicPermissionSuccess() {
        try {
            //Toast.makeText(this, "授权成功", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            e.printStackTrace();
        }

        MPermission.printMPermissionResult(false, this, BASIC_PERMISSIONS);
    }

    @OnMPermissionDenied(BASIC_PERMISSION_REQUEST_CODE)
    @OnMPermissionNeverAskAgain(BASIC_PERMISSION_REQUEST_CODE)
    public void onBasicPermissionFailed() {
        try {
            Toast.makeText(this, "未全部授权，部分功能可能无法正常运行！", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            e.printStackTrace();
        }

        MPermission.printMPermissionResult(false, this, BASIC_PERMISSIONS);
    }

    private void onInit() {
        // 加载主页面
        showMainFragment();
        LogUtil.ui("NIM SDK cache path=" + NIMClient.getSdkStorageDirPath());
    }

    @Override
    protected void onNewIntent(Intent intent) {
        setIntent(intent);
        onParseIntent();
    }

    @Override
    public void onBackPressed() {
        if (mainFragment != null) {
            if (mainFragment.onBackPressed()) {
                return;
            } else {
                moveTaskToBack(true);
            }
        } else {
            super.onBackPressed();
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.clear();
    }
/*
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main_activity_menu, menu);
        super.onCreateOptionsMenu(menu);
        return true;
    }

   /* @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.about:
                startActivity(new Intent(MainActivity.this, SettingsActivity.class));
                break;
            case R.id.create_normal_team:
                ContactSelectActivity.Option option = TeamHelper.getCreateContactSelectOption(null, 50);
                NimUIKit.startContactSelector(MainActivity.this, option, REQUEST_CODE_NORMAL);
                break;
            case R.id.create_regular_team:
                ContactSelectActivity.Option advancedOption = TeamHelper.getCreateContactSelectOption(null, 50);
                NimUIKit.startContactSelector(MainActivity.this, advancedOption, REQUEST_CODE_ADVANCED);
                break;
            case R.id.search_advanced_team:
                AdvancedTeamSearchActivity.start(MainActivity.this);
                break;
            case R.id.add_buddy:
                AddFriendActivity.start(MainActivity.this);
                break;
            case R.id.search_btn:
                GlobalSearchActivity.start(MainActivity.this);
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }*/

    private void onParseIntent() {
        Intent intent = getIntent();
        if (intent.hasExtra(NimIntent.EXTRA_NOTIFY_CONTENT)) {
            IMMessage message = (IMMessage) getIntent().getSerializableExtra(NimIntent.EXTRA_NOTIFY_CONTENT);
            switch (message.getSessionType()) {
                case P2P:
                    SessionHelper.startP2PSession(this, message.getSessionId());
                    break;
                case Team:
                    SessionHelper.startTeamSession(this, message.getSessionId());
                    break;
                default:
                    break;
            }
        } else if (intent.hasExtra(EXTRA_APP_QUIT)) {
            onLogout();
            return;
        }
    }

    private void showMainFragment() {
        if (mainFragment == null && !isDestroyedCompatible()) {
            mainFragment = new HomeFragment();
            switchFragmentContent(mainFragment);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == REQUEST_CODE_NORMAL) {
                final ArrayList<String> selected = data.getStringArrayListExtra(ContactSelectActivity.RESULT_DATA);
                if (selected != null && !selected.isEmpty()) {
                    TeamCreateHelper.createNormalTeam(MainActivity.this, selected, false, null);
                } else {
                    Toast.makeText(MainActivity.this, "请选择至少一个联系人！", Toast.LENGTH_SHORT).show();
                }
            } else if (requestCode == REQUEST_CODE_ADVANCED) {
                final ArrayList<String> selected = data.getStringArrayListExtra(ContactSelectActivity.RESULT_DATA);
                TeamCreateHelper.createAdvancedTeam(MainActivity.this, selected);
            }
        }

    }

    // 注销
    private void onLogout() {
        Toast.makeText(NimApplication.getAppContext(),"请稍等...",Toast.LENGTH_LONG).show();
        //设置客服在状态为离线
        Map<String, String> headers = new HashMap<>(1);
        String body = "?accid" + "=" + Preferences.getUserAccount() + "&onlineFlag=0&operateSource=android_app_logout";
        NimHttpClient.getInstance().init(CommonCache.getContext());
        NimHttpClient.getInstance().execute(MyConst.FIX_ONLINE_STATE_URL + body, headers, body,new NimHttpClient.NimHttpCallback() {
                    @Override
                    public void onResponse(String response, int code, Throwable exception) {
                        if (code != 200 || exception != null) {
                            Toast.makeText(NimApplication.getAppContext(),"网络响应异常，请稍后再注销",Toast.LENGTH_LONG).show();
                            return;
                        }
                        try {
                            JSONObject resObj = JSONObject.parseObject(response);
                            int resCode = resObj.getIntValue("code");
                            if(resCode!=1){
                                Toast.makeText(NimApplication.getAppContext(),"服务器响应异常，请稍后再注销",Toast.LENGTH_LONG).show();
                            }else{
                                queryUserState();
                            }
                        }catch (Exception e) {
                            Toast.makeText(NimApplication.getAppContext(),"服务器响应异常，请稍后再注销",Toast.LENGTH_LONG).show();
                        }
                    }
                });
    }

    private void queryUserState(){
        Map<String, String> headers = new HashMap<>(1);
        String body = "?accid" + "=" + Preferences.getUserAccount();
        NimHttpClient.getInstance().init(CommonCache.getContext());
        NimHttpClient.getInstance().execute(MyConst.CHECK_ONLINE_STATE_URL + body, headers, body,
                new NimHttpClient.NimHttpCallback() {
                    @Override
                    public void onResponse(String response, int code, Throwable exception) {
                        if (code != 200 || exception != null) {
                            Toast.makeText(NimApplication.getAppContext(),"网络响应异常，请稍后再注销",Toast.LENGTH_LONG).show();
                            return;
                        }
                        try {
                            JSONObject resObj = JSONObject.parseObject(response);
                            int resCode = resObj.getIntValue("code");
                            if(resCode!=0){
                                Toast.makeText(NimApplication.getAppContext(),"注销失败，请稍后再试",Toast.LENGTH_LONG).show();
                            }else{
                                Toast.makeText(NimApplication.getAppContext(),"注销成功！",Toast.LENGTH_LONG).show();
                                Preferences.saveUserToken("");
                                // 清理缓存&注销监听
                                LogoutHelper.logout();
                                // 启动登录
                                LoginActivity.start(MainActivity.this);
                                NIMClient.getService(AuthService.class).logout();
                                finish();
                            }
                        }catch (Exception e) {
                            Toast.makeText(NimApplication.getAppContext(),"服务器响应异常，请稍后再注销",Toast.LENGTH_LONG).show();
                        }
                    }
                });
    }
}
